package com.zhongyouyun.other.task;

import cn.hutool.core.collection.ListUtil;
import com.zhongyouyun.admin.model.JobModel;
import com.zhongyouyun.admin.service.JobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 应用启动后，初始化任务
 */
@Component
public class QuartzRunner implements CommandLineRunner {


    @Autowired
    private Scheduler scheduler;
    @Autowired
    private JobService jobService;
    @Override
    public void run(String... args) throws Exception {
        System.out.println("---------------------222222222222222222222222222222222----------------------------------");
        List<JobModel> list = jobService.list();
        if (null != list && list.size() > 0) {
            //处理Job
            for (JobModel job : list) {
                if ("1".equals(job.getIsStart())) {
                    JobKey jobKey = new JobKey(job.getServiceName(), "group");
                    JobDetail jobDetail = JobBuilder.newJob(BaseJob.class)
                            .withIdentity(jobKey)
                            .usingJobData("businessParam", job.getRemark())
                            .usingJobData("className", job.getServiceClass())
                            .usingJobData("methodName", job.getMethodName())
                            .build();
                    TriggerKey triggerKey = new TriggerKey(job.getServiceName(), "group");
                    Trigger trigger = TriggerBuilder.newTrigger()
                            .withIdentity(triggerKey)
                            .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()).withMisfireHandlingInstructionDoNothing())
                            .forJob(jobDetail)
                            .build();
                    JobDetail jobDetailOld = scheduler.getJobDetail(jobKey);
                    Trigger triggerOld = scheduler.getTrigger(triggerKey);
                    if (triggerOld != null) {
                        scheduler.rescheduleJob(triggerKey, trigger);
                    } else {
                        if (jobDetailOld == null) {
                            scheduler.scheduleJob(jobDetail, trigger);
                        } else {
                            scheduler.scheduleJob(trigger);
                        }
                    }

                }

            }
        }
    }
}
